<?php


namespace app\controller\admin;


use app\BaseController;
use app\common\exception\ApiException;
use app\service\utils\UploadService;


class FileController extends BaseController
{

    /**
     * 图片上传
     * @return \think\response\Json
     */
    public function upload()
    {
        try {
            $uid = $this->request->middleware('userId');
            $file = $this->request->file('file');
            $result = UploadService::upload($uid, $file);
            return $this->success($result);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 上传图片到本地
     * @return \think\response\Json
     */
    public function uploadImage()
    {
        try {
            $uid = $this->request->middleware('userId');
            $file = $this->request->file('file');
            $result = UploadService::upload($uid, $file);
            return json([
                "errno" => 0,
                "data" => [
                    'url' => $this->request->domain() . $result['src'],
                ]
            ]);
        } catch (\Exception $exception) {
            return json([
                "errno" => 1,
                "message" => $exception->getMessage()
            ]);
        }
    }

    /**
     *腾讯地图关键词查找
     * @return \think\response\Json
     */
    public function getSearchList()
    {
        try {
            $key = $this->request->param('key', 'PU5BZ-NNMKZ-PGLXI-ZJUUJ-FWZ62-7GBV4', 'trim');
            $keyword = $this->request->param('keyword', '', 'trim');
            $url = 'https://apis.map.qq.com/ws/place/v1/suggestion?key=' . $key . '&keyword=' . $keyword;
            $result = curl_get($url);
            if(!$result){
                throw new ApiException('请输入准确的地址');
            }
            $result = json_decode($result, true);
            if ($result['status'] != 0) {
                throw new ApiException($result['message']);
            }
            $result = $result['data'];
            return $this->success($result);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}
